package cn.glutnn.service.impl;

import cn.glutnn.mapper.BusinessMapper;
import cn.glutnn.mapper.OrdersMapper;
import cn.glutnn.service.BusinessService;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import cn.glutnn.entity.Business;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 商家表(Business)表服务实现类
 *
 * @author msh
 * @since 2025-01-06 23:12:44
 */
@Service("businessService")
public class BusinessServiceImpl extends ServiceImpl<BusinessMapper, Business> implements BusinessService {

    @Resource
    private OrdersMapper orderMapper;

    /**
     * 更新商家月销量
     */
    @Scheduled(cron = "0 0 1 * * ?") // 每天凌晨1点执行
    public void updateMonthlySales() {
        // 获取所有商家
        List<Business> businesses = list();

        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime monthAgo = now.minusMonths(1);

        for (Business business : businesses) {
            // 统计近30天的已完成订单数量
            Integer monthlySales = orderMapper.countMonthlySales(business.getBusinessId(), monthAgo);
            // 更新商家月销量
            update(new LambdaUpdateWrapper<Business>()
                    .eq(Business::getBusinessId, business.getBusinessId())
                    .set(Business::getMonthlySales, monthlySales));
        }
    }

    /**
     * 更新商家月销量 (+1)
     */
    public void incrementMonthlySales(Integer businessId) {
        // 使用SQL直接增加月销量
        update(new LambdaUpdateWrapper<Business>()
                .eq(Business::getBusinessId, businessId)
                .setSql("monthly_sales = monthly_sales + 1"));
    }
}

